package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.JobKnowledgeDetailActivity;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.activity.SkillDetailActivity;
import com.jp.knowledge.adapter.JobKnowledgeDataAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.BaseActivity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.IntegralBuyActivity;
import com.jp.knowledge.my.activity.ToBeVipOrganize;
import com.jp.knowledge.my.activity.VipActivity;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.Serializable;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/7/12.
 */

public class JobKnowledgeDataFragment extends Fragment implements View.OnClickListener, JobKnowledgeDataAdapter.ItemClickListener, ResultSubscriber.OnResultListener {

	private static final int PAY_CODE = 0x01;

	protected Context mContext;
	protected PositionKnowlegeMode data;
	private List<PositionKnowlegeMode.ListBeanX> listDatas;

	private View contentView;
	@ViewInject(R.id.permissionView)
	private LinearLayout remindView;
	@ViewInject(R.id.remind_img)
	private ImageView remindImg;
	@ViewInject(R.id.remind_text)
	private TextView remindText;
	@ViewInject(R.id.remind_btn)
	private TextView remindBtn;
	@ViewInject(R.id.content_rv)
	private RecyclerView contentRv;

	private CommDialog payDialog;
	protected JobKnowledgeDataAdapter adapter;

	private LocalBroadCast localBroadCast;
	private LocalBroadcastManager localBroadcastManager;

	public static JobKnowledgeDataFragment newInstance(PositionKnowlegeMode data) {
		JobKnowledgeDataFragment fragment = new JobKnowledgeDataFragment();
		Bundle bundle = new Bundle();
		bundle.putSerializable("data", data);
		fragment.setArguments(bundle);
		return fragment;
	}

	public PositionKnowlegeMode getData() {
		return data;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (contentView == null) {
			mContext = getContext();
			data = (PositionKnowlegeMode) getArguments().getSerializable("data");
			if (data != null)
				listDatas = data.getList();
			contentView = View.inflate(mContext, R.layout.fragment_job_knowledge_data, null);
			x.view().inject(this, contentView);
			contentRv.setHasFixedSize(true);
			contentRv.setLayoutManager(new LinearLayoutManager(mContext));
			adapter = new JobKnowledgeDataAdapter(mContext, listDatas);
			contentRv.setAdapter(adapter);
			remindBtn.setTag(0);
			remindBtn.setOnClickListener(this);
			adapter.setItemClickListener(this);
			payDialog = new CommDialog(mContext);
			payDialog.setRightListener(this);
			payDialog.setTag(false);
			initBroadcase();
			setRemindView(data);
		}
		return contentView;
	}

	@Override
	public void onDestroy() {
		localBroadcastManager.unregisterReceiver(localBroadCast);
		super.onDestroy();
	}

	private void initBroadcase(){
		localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
			@Override
			public void done(Context context, Intent intent) {
				if(LocalBroadCast.LOGIN_SUCCESS_BROD.equals(intent.getAction()) && remindBtn.getVisibility() == View.VISIBLE)
					remindBtn.setVisibility(View.GONE);
			}
		});
		localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
		localBroadcastManager.registerReceiver(localBroadCast, new IntentFilter(LocalBroadCast.LOGIN_SUCCESS_BROD));
	}

	public void updateView(PositionKnowlegeMode data) {
		this.data = data;
		if (this.data == null)
			this.listDatas = null;
		else
			this.listDatas = this.data.getList();
		if (adapter != null)
			adapter.updateAdapter(this.listDatas);
		setRemindView(data);
	}

	private void setRemindView(PositionKnowlegeMode data) {
		if (contentView == null)
			return;
		remindView.setVisibility(View.VISIBLE);
		remindImg.setImageResource(R.mipmap.no_data_hint);
		remindBtn.setVisibility(View.GONE);
		if (data == null) {
			remindText.setText("暂时没有数据~");
		} else if (data.getState() == 0) {
//            String str = "";
//            switch (infoData.getType()) {
//                case 1:     str = "文章"; break;
//                case 22:    str = "文库"; break;
//                case 12:    str = "素材"; break;
//                case 26:    str = "专辑"; break;
//                case 8:     str = "产品"; break;
//                default:    str = "内容"; break;
//            }
//            remindText.setText(str + "因版权问题已被删除");
			remindText.setText("内容因版权问题已被删除~");
		} else if (data.getState() == 2) {
			remindImg.setImageResource(R.mipmap.message_prompt);
			remindText.setText("栏目即将开放，敬请等候~");
		} else {
			remindText.setText(data.getViewPrompt());
			remindBtn.setVisibility(View.VISIBLE);
			remindBtn.setTag(data.getViewPermit());
			switch (data.getViewPermit()) {
				case -1:    // -1 需先登录
				case 6:     // 6 次数超过100
					remindBtn.setText("登陆");
					break;
				case 2:     // 2 用户可见
				case 3:     // 3 企业可见
				case 9:
					remindBtn.setVisibility(View.GONE);
					break;
				case 1:     // 1 用户VIP可见
					remindBtn.setText("我要升级");
					break;
				case 7:     // 7 次数超过1000
					remindBtn.setText("我要成为VIP企业");
					break;
				case 5:     // 5 企业VIP可见
					UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
					if (userData == null || userData.getCompanyList() == null || userData.getCompanyList().size() == 0) {
						remindBtn.setVisibility(View.GONE);
						remindText.setText("你无权限阅读");
					} else{
						remindBtn.setText("我要成为VIP企业");
					}
					break;
				case 4:     // 4 付费（有两种付费方式）
					remindText.setText(String.format("需支付%d知识币才能查看", data.getIntegral()));
					remindBtn.setText("付费");
					break;
				case 0:     // 0 允许查看
				default:
					if (data.getList() == null || data.getList().size() == 0) {
						remindText.setText("暂时没有数据~");
						remindBtn.setVisibility(View.GONE);
					} else {
						remindView.setVisibility(View.GONE);
					}
			}
		}
		if (remindView.getVisibility() == View.VISIBLE)
			contentRv.setVisibility(View.GONE);
		else
			contentRv.setVisibility(View.VISIBLE);
	}

	@Override
	public void onItemClick(int mainPosition, int subPosition) {
		PositionKnowlegeMode.ListBeanX.ListBean listBean = data.getList().get(mainPosition).getList().get(subPosition);
		startActivity(new Intent(mContext, JobKnowledgeDetailActivity.class)
				.putExtra("name", listBean.getName())
				.putExtra("id", listBean.getId()));
	}

	@Override
	public void onClick(View v) {
		if (v == remindBtn) {
			int viewPermit = (int) v.getTag();
			if (viewPermit == -1) {           // 登陆
				startActivity(new Intent(mContext, LoginActivity.class));
			} else if (viewPermit == 1) {   // 升级 VIP
				startActivity(new Intent(mContext, VipActivity.class));
			} else if (viewPermit == 5) {    // 成为 VIP 企业
				startActivity(new Intent(mContext, ToBeVipOrganize.class));
			} else if (viewPermit == 4) {        // 付费
				UserData userData = ((JpApplication) getActivity().getApplication()).getUserData();
				if (userData == null || userData.getIsLogin() != 1) {
					startActivity(new Intent(mContext, LoginActivity.class));
					return;
				}
				if (userData.getIntegralNum() >= data.getIntegral()) {
					payDialog.setTag(true);
					payDialog.setContent("是否确定支付" + data.getIntegral() + "知识币下载内容？");
				} else {
					payDialog.setTag(false);
					payDialog.setContent("你当前知识币不足，是否充值知识币？");
				}
				payDialog.show();
			}
		} else if(v.getId() == R.id.right_btn){
			if((boolean)payDialog.getTag()){
				JsonObject param = new JsonObject();
				param.addProperty("type", 0);
				param.addProperty("id", data.getId());
				param.addProperty("integral", data.getIntegral());
				HttpHelper.getInstance(mContext).integralPurchase(param, PAY_CODE, this);
			} else{
				startActivity(new Intent(mContext, IntegralBuyActivity.class));
			}
		}
	}

	@Override
	public void onStart(int requestType) {
		if(requestType == PAY_CODE)
			((BaseActivity)getActivity()).showLoading();
	}

	@Override
	public void onCompleted(int requestType) {
		if(requestType == PAY_CODE)
			((BaseActivity)getActivity()).cancleLoading();
	}

	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
	}

	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(mContext, data.getMessage());
			onError(requestType);
		} else if(requestType == PAY_CODE){
			remindBtn.setVisibility(View.GONE);
			LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent(LocalBroadCast.PAY_TO_READ));
		}
	}
}
